package com.magic.cart.service.impl;

import com.magic.cart.client.GoodsClient;
import com.magic.cart.interceptor.LoginInterceptor;
import com.magic.cart.pojo.Cart;
import com.magic.cart.service.CartService;
import com.magic.common.pojo.UserInfo;
import com.magic.common.utils.JsonUtils;
import com.magic.item.pojo.Sku;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lan.jianyuan
 * @create 2021-02-17-16:23
 */
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private GoodsClient goodsClient;
    private static final String KEY_PREFIX = "user:cart:uid:";
    @Override
    public void addCart(Cart cart) {
        // 获取登录用户
        UserInfo user = LoginInterceptor.getLoginUser();
        // Redis的key
        String key = KEY_PREFIX + user.getId();
        // 获取hash操作对象
        BoundHashOperations<String, Object, Object> hashOps = this.redisTemplate.boundHashOps(key);
        String keys = cart.getSkuId().toString();
        Integer num = cart.getNum();
        // 判断当前的商品是否在购物车中
        if (hashOps.hasKey(keys)) {
            // 在，更新数量
            String cartJson = hashOps.get(keys).toString();
            cart = JsonUtils.toBean(cartJson, Cart.class);
            cart.setNum(cart.getNum() + num);
        }
        else {
            // 不在，新增购物车
            Sku sku = this.goodsClient.querySkuById(cart.getSkuId());
            cart.setUserId(user.getId());
            cart.setTitle(sku.getTitle());
            cart.setOwnSpec(sku.getOwnSpec());
            cart.setImage(StringUtils.isBlank(sku.getImages()) ? "" : StringUtils.split(sku.getImages(), ",")[0]);
            cart.setPrice(sku.getPrice());
        }
        hashOps.put(keys, JsonUtils.toString(cart));
    }
    
    @Override
    public List<Cart> queryCarts() {
        UserInfo loginUser = LoginInterceptor.getLoginUser();
        //判断用户是否有购物车记录
        if (!this.redisTemplate.hasKey(KEY_PREFIX + loginUser.getId())) {
            return  null;
        }
        //获取用户的购物车记录
        BoundHashOperations<String, Object, Object> ops = this.redisTemplate.boundHashOps(KEY_PREFIX + loginUser.getId());
        //获取购物车Map中所有Cart值集合
        List<Object> values = ops.values();
        //如果购物车集合为空，直接返回null
        if (CollectionUtils.isEmpty(values)) {
            return null;
        }
        //把List<Object>集合转化为List<Cart>集合
        return values.stream().map(value -> JsonUtils.toBean(value.toString(), Cart.class)).collect(Collectors.toList());
    }
    
    @Override
    public void updateNum(Cart cart) {
        UserInfo userInfo = LoginInterceptor.getLoginUser();
        //判断用户是否有购物车记录
        if (!this.redisTemplate.hasKey(KEY_PREFIX + userInfo.getId())) {
            return;
        }
        Integer num = cart.getNum();
        //获取用户的购物车记录
        BoundHashOperations<String, Object, Object> ops = this.redisTemplate.boundHashOps(KEY_PREFIX + userInfo.getId());
        String toString = ops.get(cart.getSkuId().toString()).toString();
        cart = JsonUtils.toBean(toString, Cart.class);
        cart.setNum(num);
        ops.put(cart.getSkuId().toString(), JsonUtils.toString(cart));
    }
    
    @Override
    public void deleteCart(String skuId) {
        // 获取登录用户
        UserInfo user = LoginInterceptor.getLoginUser();
        String key = KEY_PREFIX + user.getId();
        BoundHashOperations<String, Object, Object> hashOps = this.redisTemplate.boundHashOps(key);
        hashOps.delete(skuId);
    }
}
